package com.bicon.botu.mall.goods.api;


import com.alibaba.fastjson.JSONObject;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.entity.TranceDetail;
import com.bicon.botu.mall.goods.entity.TranceInfo;
import com.bicon.botu.mall.goods.service.ITranceInfoService;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户定制信息
 *
 * @author SYG
 * @date 2017/8/12
 */
@CrossOrigin
@RestController
@RequestMapping("V1.0.0/api/userTrance")
public class UserTranceApi extends BaseController {

    @Autowired
    private ITranceInfoService tranceInfoService;

    /**
     * 保存或修改定制信息
     *
     * @param userId
     * @param beforeText   前身文字
     * @param afterText    后身文字
     * @param jsonString   微量元素对象json
     * @param tranceInfoId 定制id
     * @param productId    商品id
     * @return
     */
    @RequestMapping(value = "saveUserTranceInfo", method = RequestMethod.POST)
    public BaseResult saveUserTranceInfo(@RequestParam String userId,
                                         @RequestParam(required = false) String beforeText, @RequestParam(required = false) String afterText,
                                         @RequestParam String jsonString, @RequestParam(required = false) String tranceInfoId,
                                         @RequestParam String productId) {
        TranceInfo tranceInfo = new TranceInfo();
        tranceInfo.setUserId(userId);
        tranceInfo.setAfterText(afterText);
        tranceInfo.setBeforeText(beforeText);
        tranceInfo.setProductId(productId);
        if (null != tranceInfoId && tranceInfoId != "") {
            tranceInfo.setId(tranceInfoId);
            tranceInfo.preUpdate();
        } else {
            tranceInfo.preInsert();
        }

        List<TranceDetail> list = JSONObject.parseArray(jsonString, TranceDetail.class);
        List<TranceDetail> newList = new ArrayList<>();
        if (null != tranceInfoId && tranceInfoId != "") {
            for (TranceDetail detail : list) {
                detail.preUpdate();
                newList.add(detail);
            }
        } else {
            for (TranceDetail detail : list) {
                detail.preInsert();
                detail.setTranceInfoId(tranceInfo.getId());
                newList.add(detail);
            }
        }
        tranceInfoService.saveTranceInfo(tranceInfo, newList);
        return sendResult(GoodsConstants.RESPONSE_CODE_200, GoodsConstants.RESPONSE_MESSAGE_200, tranceInfo);

    }

}
